package com.learn.project2.config.typehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import javax.lang.model.element.VariableElement;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @description: TODO String 转换为 String[]
 * @author 岳子昂
 * @date 2022-01-07 18:05
 * @version 1.0
 */
@MappedTypes(String[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringArrayTypeHandler implements TypeHandler<String[]> {

    // jackson
    ObjectMapper objectMapper = new ObjectMapper();

    // 输入 string[] to string
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, String[] strings, JdbcType jdbcType) throws SQLException {
        String value = null;
        try {
            value = objectMapper.writeValueAsString(strings);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        preparedStatement.setString(i,value);
    }

    // 输出 string to string[]
    @Override
    public String[] getResult(ResultSet resultSet, String columnName) throws SQLException {
        String columnValue = resultSet.getString(columnName);
        try {
            String[] strings = objectMapper.readValue(columnValue,String[].class);
            return strings;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return new String[0];
    }

    @Override
    public String[] getResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String columnValue = resultSet.getString(columnIndex);
        try {
            String[] strings = objectMapper.readValue(columnValue,String[].class);
            return strings;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return new String[0];
    }

    @Override
    public String[] getResult(CallableStatement callableStatement, int i) throws SQLException {
        String columnValue = callableStatement.getString(i);
        try {
            String[] strings = objectMapper.readValue(columnValue,String[].class);
            return strings;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return new String[0];
    }
}
